import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Icon from '../Icon';
import './style/index.less';

function noop() { }

export default class Button extends React.Component {
  static defaultProps = {
    prefixCls: 'ant-btn',
    loading: false,
    type: '',
    htmlType: 'button',
    className: '',
    onClick: noop,
    icon: ''
  };

  static propTypes = {
    type: PropTypes.string,
    shape: PropTypes.oneOf(['circle']),
    htmlType: PropTypes.oneOf(['submit', 'button', 'reset']),
    onClick: PropTypes.func,
    loading: PropTypes.oneOfType([PropTypes.bool]),
    className: PropTypes.string,
    icon: PropTypes.string
  }

  constructor(props) {
    super(props);

    this.state = {};
    this.handleClick = this.handleClick.bind(this);
  }

  componentWillUnmount() {
    if (this.timeout) {
      clearTimeout(this.timeout);
    }
  }

  handleClick(e) {
    const { onClick } = this.props;
    this.setState({ clicked: true });
    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => this.setState({ clicked: false }), 500);
    if (onClick) {
      onClick(e);
    }
  }

  render() {
    const { type, shape, loading, className, htmlType, children, prefixCls, icon, ...others
    } = this.props;

    const { clicked } = this.state;

    const classes = classNames(prefixCls, {
      [`${prefixCls}-${type}`]: type,
      [`${prefixCls}-${shape}`]: shape,
      [`${prefixCls}-loading`]: loading,
      [`${prefixCls}-clicked`]: clicked,
    }, className);

    const iconType = loading ? 'loading' : icon;
    const iconNode = iconType ? <Icon type={iconType} /> : null;

    return (
      <button
        {...others}
        type={htmlType || 'button'}
        className={classes}
        onClick={this.handleClick}
      >
        {iconNode}{children}
      </button>
    );
  }
}
